import { memo, useEffect, useMemo, useRef, useState } from 'react'
import styles from './index.module.scss'
import ListQuestionItem from '@/components/listQuestionItem'
import { Empty, Spin, Typography } from 'antd'

import { useTitle, useDebounceFn, useRequest } from 'ahooks'
import ListSearch from '@/components/ListSearch'
import { useSearchParams } from 'react-router-dom'
import { getQuestionList } from '@/service/module/question'
import { LIST_SEARCH_PARAM_KEY } from '@/constant'

const { Title } = Typography

const List = memo(() => {
  //修改网页标题
  useTitle('小慕问卷-我的问卷')

  const [started, setStarted] = useState(false) //是否已经开始加载 (防抖,有延迟时间)
  const [list, setList] = useState([])
  const [page, setPage] = useState(1) //list 内部的数据,不在url参数中体现
  const [total, setTotal] = useState(0)
  const loadRef = useRef<HTMLDivElement>(null)

  //记录是否还有更多数据未加载
  const hasMoreData = list.length < total
  const [searchParams] = useSearchParams()
  const keyword = searchParams.get(LIST_SEARCH_PARAM_KEY) || ''

  useEffect(() => {
    setStarted(false)
    setPage(1)
    setList([])
    setTotal(0)
  }, [keyword])

  //真正加载数据
  const { run, loading } = useRequest(
    async () => {
      const data = await getQuestionList({
        keyword,
        page,
      })

      return data
    },
    {
      manual: true,
      onSuccess(result) {
        const { list: l = [], total = 0 } = result
        setList(list.concat(l))
        setTotal(total)
        setPage(page + 1)
      },
    }
  )

  //尝试加载更多数据 - 防抖
  const { run: tryLoadMore } = useDebounceFn(
    () => {
      const dom = loadRef.current
      if (dom == null) return
      const rect = dom.getBoundingClientRect()
      if (rect == null) return
      const { bottom } = rect
      if (bottom <= document.body.clientHeight) {
        run()
        setStarted(true)
      }
    },
    {
      wait: 1000,
    }
  )

  //1.当组件初次渲染和 搜索关键字变化时触发
  useEffect(() => {
    tryLoadMore()
  }, [searchParams])

  //2.当页面滚动时,要尝试触发加载
  useEffect(() => {
    if (hasMoreData) {
      window.addEventListener('scroll', tryLoadMore)
    }
    return () => {
      window.removeEventListener('scroll', tryLoadMore) //组件销毁时 解绑事件
    }
  }, [searchParams, hasMoreData])

  const loadMoreContentElem = useMemo(() => {
    if (!started || loading) return <Spin />
    if (total === 0) return <Empty description="暂无数据" />
    if (!hasMoreData) return <span>没有更多了...</span>
    return <span>开始加载下一页</span>
  }, [started, loading, total, hasMoreData])

  return (
    <>
      <div className={styles.list}>
        <div className={styles.header}>
          <Title level={3}>我的问卷</Title>
          <ListSearch />
        </div>
        <div className={styles.QList}>
          {list.length !== 0 &&
            list.map((question: any) => {
              return <ListQuestionItem question={question} key={question.id} />
            })}
        </div>
        <div className={styles.footer}>
          <div ref={loadRef}>{loadMoreContentElem}</div>
        </div>
      </div>
    </>
  )
})

export default List
